package com.CmJava.utils;




import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.JwtMap;
import io.jsonwebtoken.impl.compression.GzipCompressionCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.SimpleFormatter;

@Component
public class TokenManager {
    //过期时间，单位毫秒
    private static final long deathTime = 24 * 60* 60*1000;
    //编码密钥
    private static final String encodeKey="123456";


    public static String getToken(User user, HttpServletRequest request){
        Iterator<GrantedAuthority> iterator = user.getAuthorities().iterator();
        String authorities="";
        while (iterator.hasNext()){
            authorities+=iterator.next().getAuthority();
        }

        String token = Jwts.builder().
                setSubject(user.getUsername()).//标题
                claim("authorities",authorities).
                claim("userIp",request.getRemoteAddr()).
                claim("loginTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).
                setExpiration(new Date(System.currentTimeMillis() + deathTime)).
                signWith(SignatureAlgorithm.HS512, encodeKey).
                compressWith(new GzipCompressionCodec()).compact();
        return token;
    }


    public static com.CmJava.entity.User tokenToUser(String token){
        Claims body = Jwts.parser().setSigningKey(encodeKey).parseClaimsJws(token).getBody();
        String authorities = body.get("authorities", String.class);
        String userName = Jwts.parser().setSigningKey(encodeKey).parseClaimsJws(token).getBody().getSubject();
        return new com.CmJava.entity.User(-1,userName,"",authorities,"","");
    }

    public static String getUserIp(String token){
        Claims body = Jwts.parser().setSigningKey(encodeKey).parseClaimsJws(token).getBody();
        String ip = body.get("userIp", String.class);
        return ip;
    }

    public static String getLoginTime(String token){
        Claims body = Jwts.parser().setSigningKey(encodeKey).parseClaimsJws(token).getBody();
        String loginTime = body.get("loginTime", String.class);
        return loginTime;
    }


    public void deleteToken(String token){

    }
}
